package com.sunlands.qdcy.tongzhuo.config;

import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.paths.RelativePathProvider;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.ServletContext;
import java.util.Arrays;
import java.util.List;

/**
 * <p>swagger配置</p>
 * @package: com.sunlands.zlcx.mpmsgservice.config
 * @date Created in 2017/11/30 15:42
 * @copyright: Copyright (c) founders
 */
@EnableSwagger2
@Configuration
@ConfigurationProperties(prefix = "swagger")
@Setter
public class SwaggerConfiguration {

    @Value("${swagger.title}")
    String title;

    @Value("${swagger.description}")
    String description;

    @Value("${swagger.basePackage}")
    String basePackage;

    @Value("${swagger.version}")
    String version;

    @Value("${swagger.contact.name}")
    String contactName;

    @Value("${swagger.contact.email}")
    String contactEmail;

    @Value("${swagger.host}")
    String host;

    @Value("${spring.application.name}")
    String applicationName;

    @Autowired
    private ServletContext servletContext;

    /**
     * 这个配置是因为迁移到k8s,不再使用zuul后加的配置
     */
    private List<String> localPath = Arrays.asList("localhost", "127.0.0.1");

    @Bean
    public Docket createRestApi() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .host(host)
                .select()
                .apis(RequestHandlerSelectors.basePackage(basePackage))
//                .paths(PathSelectors.any())
                .build();
        if (!localPath.contains(host)) {
            docket.pathProvider(new RelativePathProvider(servletContext) {
                @Override
                public String getApplicationBasePath() {
                    return "/" + applicationName;
                }
            });
        }
        return docket;
    }

    @Bean
    public ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(title)
                .contact(new Contact(contactName, null, contactEmail))
                .description(description)
                .version(version)
                .build();
    }

}
